# -*- coding: utf-8 -*-
# @Time : 2023/11/29 13:47:03
# @Author : sacon
# @File : phone.py

import random
import re

import requests
import time
from loguru import logger


class Phone():
    def __init__(self):
        self.Api_domain_list = ['http://api.my531.com']

        self.username = 'chang123456789'
        self.password = 'chang123456789'

        self.token = self.login()
        if not self.token:
            raise ValueError('登录失败')

    def login(self):  # http://api.my531.com/Login/?username=chang123456789&password=chang123456789&type=json
        url = f'{random.choice(self.Api_domain_list)}/Login/?username={self.username}&password={self.password}&type=json'

        res = requests.get(url, timeout=20)
        if res.status_code != 200:
            logger.error(f'登录失败:{res.text}')
            raise ValueError('登录失败')
        data = res.json()['data']
        if float(data['money']) < 0:
            raise ValueError('余额不足')

        return data['token']

    def get_phone(self, item_id='37625'):
        url = f'{random.choice(self.Api_domain_list)}/GetPhone/?token={self.token}&id={item_id}&type=json'
        res = requests.get(url, timeout=20)
        if res.status_code == 200 and res.json()['message'] == 'ok':
            phone = res.json()['data']
            return phone
        else:
            logger.error(f'获取手机号失败:{res.text}')
            raise ValueError('获取手机号失败')

    def get_phone_code(self, phone, item_id='37625'):
        url = f'{random.choice(self.Api_domain_list)}/GetMsg/?token={self.token}&id={item_id}&phone={phone}&type=json'
        for i in range(30):
            res = requests.get(url, timeout=20)
            if res.status_code == 200:
                if res.json()['message'] == 'ok':
                    code_text = res.json()['data']
                    if not code_text:
                        time.sleep(5)
                        continue
                    code = re.findall(r'\d{6}', code_text)[0]
                    return code
                else:
                    logger.debug(f'暂未获取到验证码，等待5秒后继续获取 :{res.text} ')
                    time.sleep(5)
            else:
                logger.error(f'获取验证码失败:{res.text}')
                raise ValueError('获取验证码失败')
        return False

    def release_phone(self, phone, item_id='37625'):
        url = f'{random.choice(self.Api_domain_list)}/Cancel/?token={self.token}&id={item_id}&phone={phone}&type=json'
        headers = {
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)'
        }
        res = requests.get(url, headers=headers, timeout=20)
        if res.status_code == 200 and res.json()['message'] == 'ok':
            logger.debug(f'释放手机号成功:{res.text}')
            return True
        else:
            logger.error(f'释放手机号失败:{res.text}')
            return


phone_taxin_obj = Phone()
if __name__ == '__main__':
    # print(phone_taxin_obj.get_phone())
    print(phone_taxin_obj.get_phone_code("16572444055"))
